﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Filters;
using System.Web.Http.Results;
using Sharp.Infrastructure;

namespace Sharp.Portal.WebAPI
{
    ///// <summary>
    ///// 
    ///// </summary>
    //[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    //public class AuthenticateAttribute : FilterAttribute, IAuthenticationFilter
    //{

    //    /// <summary>
    //    /// 
    //    /// </summary>
    //    /// <param name="context"></param>
    //    /// <param name="cancellationToken"></param>
    //    /// <returns></returns>
    //    public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
    //    {
    //        return Task.Run(() =>
    //        {
    //            IPrincipal user = null;
    //            var headerValue = context.Request.Headers.Authorization;
    //            if (null != headerValue && headerValue.Scheme == "Basic")
    //            {
    //                var credential = Encoding.UTF8.GetString(Convert.FromBase64String(headerValue.Parameter));
    //                var split = credential.Split(':');
    //                if (split.Length == 2)
    //                {
    //                    var userName = split[0];
    //                    var userId = split[1].ToInt();

    //                    var identity = new GenericIdentity(userName);
    //                    user = new GenericPrincipal(identity, new string[0]);

    //                    HttpContext.Current.User.Identity.GetUserId() = userId;
    //                    ContactContext.Current.UserName = userName;
    //                }
    //            }
    //            context.Principal = user;
    //        }, cancellationToken);
    //    }

    //    /// <summary>
    //    /// 
    //    /// </summary>
    //    /// <param name="context"></param>
    //    /// <param name="cancellationToken"></param>
    //    /// <returns></returns>
    //    public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
    //    {

    //        return Task.Run(() =>
    //        {
    //            //var user = context.ActionContext.ControllerContext.RequestContext.Principal;
    //            //if (null != user && user.Identity.IsAuthenticated)
    //            //    return;

    //            //var parameter = $"realm={context.Request.RequestUri.DnsSafeHost}";
    //            //var challenge = new AuthenticationHeaderValue("Basic", parameter);
    //            //context.Result = new UnauthorizedResult(new[] {challenge}, context.Request);

    //        }, cancellationToken);
    //    }


    //}
}
